package com.xcyy.zjdxmjk.zjdxmjk.common;

import com.alibaba.fastjson.JSON;
import com.xcyy.zjdxmjk.zjdxmjk.entity.AccessToken;
import com.xcyy.zjdxmjk.zjdxmjk.entity.User;
import com.xcyy.zjdxmjk.zjdxmjk.entity.UserInfo;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public class HttpClient {
    /**
     * get请求传输数据
     *
     * @param url
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static String sendGetData(String url) throws ClientProtocolException, IOException {
        String result = "";

        // 创建httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 创建get方式请求对象
        HttpGet httpGet = new HttpGet(url);
        httpGet.addHeader("Content-type", "application/json");
        // 通过请求对象获取响应对象
        CloseableHttpResponse response = httpClient.execute(httpGet);

        // 获取结果实体
        // 判断网络连接状态码是否正常(0--200都数正常)
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            result = EntityUtils.toString(response.getEntity(), "utf-8");
        }
        // 释放链接
        response.close();

        return result;
    }
    public static  UserInfo login(String code) throws IOException {

        String accessTokenStr= sendGetData("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wxe7d68f45496299d7&corpsecret=EXgyTDLdr0ofBhn6vYTnFKXmFMCFk3FOmpBodFT_iDM");
        AccessToken accessToken= JSON.parseObject(accessTokenStr,AccessToken.class);
        String userStr=sendGetData("https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token="+accessToken.getAccess_token()+"&code="+code);
        User user=JSON.parseObject(userStr,User.class);
        String userInfoStr=sendGetData("https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token="+accessToken.getAccess_token()+"&userid="+user.getUserId());
        UserInfo userInfo=JSON.parseObject(userInfoStr,UserInfo.class);

        return userInfo;
    }
}
